package com.shushan.accessibility;

import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;

import com.android.permission.rom.RomType;
import com.android.permission.rom.RomUtils;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.manager.JobSchedulerManager;
import com.shushan.receiver.LockAdminReceiver;
import com.shushan.service.DaemonService;
import com.shushan.service.PlayerMusicService;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.RoundProgressView;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.SystemUtils;

import static com.android.permission.rom.RomType.EMUI_ROM;

/**
 * @ClassName: PermissionAutoOpenActivity
 * @Desciption: 权限自动开启中
 * @author: yichaohua
 * @date: 2018-07-17
 */
public class PermissionAutoOpenActivity extends BaseActivity{

    private static final String TAG = "PermissionAutoOpenActivity";

    private RoundProgressView roundProgressView;

    private boolean isOpenComplete = false;
    private boolean isOpneWindow = false;
    private boolean isUsageable = false;
    private boolean isAdminEnable = false;
    private boolean isPowerClose = false;

    private RomType romType;
    private DevicePolicyManager dpm;
    private ComponentName adminComponent;

    private int perCount;
    private int percentum = 0;

    private Handler mHandler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case 0:
                    Intent intent = new Intent(PermissionAutoOpenActivity.this,PermissionOpenActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    if((romType == RomType.SAMSUNG_ROM && Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
                            || romType == RomType.FLYME_ROM){
                        intent.putExtra("openIndex",2);
                    }else {
                        intent.putExtra("openIndex",1);
                    }
                    startActivity(intent);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.i(TAG,"onCreate()");

        setContentView(R.layout.permission_auto_open_activity);

        ScreenManager sm = new ScreenManager();
        sm.setDeepStatusBar(true,this);

        dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
        adminComponent = new ComponentName(this, LockAdminReceiver.class);

        romType = RomUtils.getRomType(this);
        Log.i(TAG,"romType=" + romType.toString());
        computePercent(romType);

        initView();

        mHandler.sendEmptyMessageDelayed(0,1000*2);
    }

    private void computePercent(RomType romType) {
        if((romType == EMUI_ROM  && RomUtils.getEmuiLeval(this) >= 14)){
            isOpenComplete = true;
            perCount = 100 /4;
        } else if((romType == RomType.SAMSUNG_ROM && Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
                || romType == RomType.FLYME_ROM){
            isPowerClose = true;
            perCount = 100 /4;
        }else {
            perCount = 100 /5;
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        Log.i(TAG,"onNewIntent()");

        boolean isAccessResult = intent.getBooleanExtra("isAccessResult",false);
        Log.i(TAG,"isAccessResult=" + isAccessResult);
        if (isAccessResult){
            boolean result = intent.getBooleanExtra("result",false);
            int resultCode = intent.getIntExtra("resultCode",0);
            Log.i(TAG,"resultCode=" + resultCode + " result=" + result);

            onAutoResult(result,resultCode);
        }
    }
    private void initView() {
        roundProgressView = findViewById(R.id.permission_auto_open_rpv);
        roundProgressView.setMax(100);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mHandler.removeCallbacksAndMessages(null);
    }

    private void onResult(int resultCode) {
        if(resultCode == 200){
            isOpenComplete = true;
            percentum += perCount;
            roundProgressView.setProgress(percentum);
        }else if(resultCode == 300){
            isOpneWindow = true;
            percentum += perCount;
            roundProgressView.setProgress(percentum);
        }else if(resultCode == 400){
            if (dpm.isAdminActive(adminComponent)) {
                isAdminEnable = true;
                percentum += perCount;
                roundProgressView.setProgress(percentum);
            }
        } else if(resultCode == 500){
            isPowerClose = true;
            percentum += perCount;
            roundProgressView.setProgress(percentum);
        }else if(resultCode == 600){
            if(SystemUtils.checkUsagePermission(this)){
                isUsageable = true;
                percentum += perCount;
                roundProgressView.setProgress(percentum);
            }else {
                isUsageable = false;

            }
        }

    }

    private void onAutoResult(boolean result,int resultCode) {
        if(result){
            onResult(resultCode);
        }

        switch (resultCode){
            case 200:
                Intent intent2 = new Intent(this,PermissionOpenActivity.class);
                intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent2.putExtra("openIndex",3);
                startActivity(intent2);
                break;
            case 300:
                Intent intent4 = new Intent(this,PermissionOpenActivity.class);
                intent4.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent4.putExtra("openIndex",5);
                startActivity(intent4);
                break;
            case 400:
                Intent intent3 = new Intent(this,PermissionOpenActivity.class);
                intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent3.putExtra("openIndex",4);
                startActivity(intent3);
                break;
            case 500:
                Intent intent1 = new Intent(this,PermissionOpenActivity.class);
                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent1.putExtra("openIndex",2);
                startActivity(intent1);
                break;
            case 600:
                doResult();
                break;
            default:
                break;
        }
    }

    private void doResult() {
        if(isOpenComplete && isOpneWindow && isUsageable
                && isAdminEnable && isPowerClose){

            SharedPreferencesUtils.setBooleanDate(Constants.MAIN_PERMISSION_HAS_SET_SHAREPREFERS_KEY,true);
            SharedPreferencesUtils.setBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY,true);
            showToast("自动授权成功");

            SharedPreferencesUtils.setBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY,true);
            Intent intent = new Intent(this, DaemonService.class);
            startService(intent);

            Intent intent1 = new Intent(this,PlayerMusicService.class);
            startService(intent1);

            //启动系统任务
            JobSchedulerManager mJobManager = JobSchedulerManager.getJobSchedulerInstance(BabyApplication.getInstance());
            mJobManager.startJobScheduler();
        }else {
            Intent intent = new Intent(this,PermissionHandOpenActivity.class);
            intent.putExtra("isOpenComplete",isOpenComplete);
            intent.putExtra("isOpneWindow",isOpneWindow);
            intent.putExtra("isUsageable",isUsageable);
            intent.putExtra("isAdminEnable",isAdminEnable);
            intent.putExtra("isPowerClose",isPowerClose);

            startActivityAllow(intent);
        }

        onBackAction();
    }
}
